package com.bugbuff.dubbo.server.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.bugbuff.common.utils.Cache;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/*
* 通用缓存拦截器
*   1、自定义拦截器处理类
*   2、将处理类创建对象加入IOC容器
*   3、配置拦截器
* */
@Component
public class RedisCacheInterceptor implements HandlerInterceptor {


    private final static ObjectMapper MAPPER=new ObjectMapper();

    @Autowired
    private RedisTemplate<String,String> redisTemplate;


    @Value("true")
    private Boolean enable;

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //设置缓存全局开关控制
        if(!enable){
            return true;
        }
       //指定放行的规则
        //3、controller方法对象
        if(!(handler instanceof HandlerMethod)){
            return true;
        }
        //1、@GetMapping
        if(!((HandlerMethod)handler).hasMethodAnnotation(GetMapping.class)){
            return true;
        }
        //2、控制get是否缓存的条件，通过自定义注解来实现
        if(!((HandlerMethod)handler).hasMethodAnnotation(Cache.class)){
            return true;
        }

        //redis获取数据
        //缓存命中
        String redisKey = createRedisKey(request);
        String cacheData = this.redisTemplate.opsForValue().get(redisKey);
        if(StringUtils.isEmpty(cacheData)){//当前的key是没有的，需要从数据库查询再存储到redis
            //缓存未命中
            return true;
        }

        //响应前端 json
        response.setContentType("application/json; charset=utf-8");
        response.getWriter().write(cacheData);

        return false;
    }

    /**
     * 生成redis中的key，规则：SERVER_CACHE_DATA_MD5(url + param + token)
     *
     * @param request
     * @return
     */
    public static String createRedisKey(HttpServletRequest request) throws Exception {
        String url = request.getRequestURI();
        String param = MAPPER.writeValueAsString(request.getParameterMap());
        String token = request.getHeader("Authorization");

        String data = url + "_" + param + "_" + token;
        return "SERVER_CACHE_DATA_" + DigestUtils.md5Hex(data);
    }
}
